/**
 * @description setting module
 * @author Zhangbin
 */
import * as types from '@/store/mutation-types'
import { SettingType, SettingKeyType } from '@/store/types'
import { palettes, themeMode } from '@/config/setting.config'
import { setSettings, getSettings } from '@/utils/cookies'
import { changeTheme } from "@/utils/setting";
import * as cssVars from '@/styles/theme/variables.less'
import { ANTD } from "@/config/antd.config";

const state: SettingType = {
  palettes: palettes,
  selectedPalette: (getSettings('settings') as SettingKeyType).palette,
  themeMode: themeMode,
  selectedMode: (getSettings('settings') as SettingKeyType).mode,
}

const mutations = {
  [types.SET_PALETTE](state: SettingType, payload: string) {
    const tempObj = Object.assign({}, {
      palette: payload,
      mode: state.selectedMode
    });
    setSettings('settings', tempObj)
    state.selectedPalette = payload
  },
  [types.SET_MENUMODE](state: SettingType, payload: string) {
    const tempObj = Object.assign({}, {
      palette: state.selectedPalette,
      mode: payload
    });
    setSettings('settings', tempObj)
    state.selectedMode = payload;
    const mode = Object.values(state.themeMode)[Number(state.selectedMode)];
    const antdTheme = (ANTD.theme as {[key: string]: any})[mode]
    changeTheme(antdTheme, 'isChange', mode);
    document.documentElement.setAttribute('data-theme', `theme-${mode}`)
  },
  [types.CHANGE_THEME](state: SettingType, payload: { [key: string]: string }) {
    const inx = Number(payload.inx)
    const item: string = state.palettes[inx];
    const vars = {
      "primary-color": item,
      "success-color": item,
      "btn-primary-bg": item,
    };
    changeTheme(vars, payload.flag);
  },
  [types.CLEAR_SETTING](state: SettingType) {
    // reset default theme
    state.selectedPalette = '';
    state.selectedMode = '';
    const color = cssVars.primaryColor
    const vars = {
      "primary-color": color,
      "success-color": color,
      "btn-primary-bg": color,
    };
    changeTheme(vars, 'isInit');
  },
}

const actions = {

}

export const settingStore = {
  state,
  mutations,
  actions
}
